import React from 'react';
import './prescription.less';
import { Breadcrumb, Icon, DatePicker, Select, Button, Table, Pagination, Row, Col, Modal, message, Input } from 'antd';
import { Link } from 'react-router';
import moment from 'moment';
import $ from 'jquery';
import Config from '../../common/config';

const Option = Select.Option;
const config = new Config();
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token');

class Prescription extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            beginDate: null, // 开始时间
            endDate: null, // 结束时间
            status: undefined, //处方状态
            orderStatus: undefined, //订单状态
            page: 1, // 当前页
            pageSize: 10, // 每页显示的条数
            total: 0, // 总数
            totalMoney: 0, // 总价
            rowKeys: [], //表格选中的行
            data: [], // 订单数据
        }
        this.onSelectChange = this.onSelectChange.bind(this)
        this.onChangePage = this.onChangePage.bind(this)
    }

    componentDidMount() {
        this.getData();
    }

    //获取订单数据
    getData() {
        let beginDate = this.state.beginDate;
        if (beginDate) {
            beginDate = beginDate.format('YYYY-MM-DD');
        }
        let endDate = this.state.endDate;
        if (endDate) {
            endDate = endDate.format('YYYY-MM-DD');
        }
        $.ajax({
            url: `${config.JuseOrder}/prescriptionOrder/list`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                beginDate,
                endDate,
                status: this.state.status,
                orderStatus: this.state.orderStatus,
                page: this.state.page,
                pageSize: this.state.pageSize
            },
            success: (res) => {
                console.log('订单数据', res);
                let totalMoney = 0;
                res.data.rows.forEach(item => {
                    totalMoney += Number(item.orderMoney);
                    item.key = item.orderId;
                })
                totalMoney = totalMoney.toFixed(2);
                if (res.code === 200) {
                    this.setState({
                        data: res.data.rows,
                        total: res.data.count,
                        totalMoney
                    });
                }
            }
        });
    }

    // 选择时间
    changeFilterTime(key, date) {
        if (key == 0) {
            this.setState({
                beginDate: date,
            })
        } else {
            this.setState({
                endDate: date,
            })
        }
    }

    // 处方状态
    changeCFstate(val) {
        this.setState({ status: val });
    }

    // 订单状态
    changeorderStatus(val) {
        this.setState({ orderStatus: val });
    }

    //筛选提交按钮
    filterOrders(key) {
        if (key) {
            this.setState({
                page: 1
            }, () => {
                this.getData();
            });
        } else {
            this.setState({
                beginDate: null,
                endDate: null,
                status: undefined,
                orderStatus: undefined
            }, () => {
                this.getData();
            });
        }
    }

    //批量审核订单
    penddingManyOrder() {
        Modal.confirm({
            title: '是否现在进行操作？',
            content: '该' + this.state.rowKeys.length + '条订单一经确认后即将转入待发货订单',
            onOk: () => {
                $.ajax({
                    url: `${config.JuseOrder}/prescriptionOrder/batchAudit`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        orderIdList: this.state.rowKeys
                    },
                    success: (data) => {
                        console.log('批量审核', data);
                        if (data.code === 200) {
                            this.setState({
                                rowKeys: []
                            });
                            this.getData();
                        }
                    }
                });
            }
        })
    }

    // 切换分页
    onChangePage(page) {
        this.setState({
            page
        }, () => {
            this.getData();
        });
    }
    //table表格 选中行事件
    onSelectChange(rowKeys) {
        //这个rowKey 是dat中的key，可以将key写成数据id，则拿到的就是id的数组
        console.log('表格行的key: ', rowKeys);
        this.setState({ rowKeys });
    }
    render() {
        const columns = [
            { title: '订单编号', dataIndex: 'orderId', width: '14%' },
            { title: '收货人', dataIndex: 'consigneeName', width: '6%' },
            { title: '联系方式', dataIndex: 'consigneePhone', width: '10%' },
            {
                title: '订单金额', width: '10%', dataIndex: '', render(record) {
                    return `${record.orderMoney}(${record.paymentMethod})`
                }
            },
            {
                title: '预约信息状态', dataIndex: '', width: '10%', render(record) {
                    let text;
                    switch (record.prescriptionStutas) {
                        case 1:
                            text = '待审核';
                            break;
                        case 2:
                            text = '通过';
                            break;
                        case 3:
                            text = '不通过';
                            break;
                    }
                    return text;
                }
            },
            {
                title: '支付状态', dataIndex: '', width: '10%', render(record) {
                    if (record.prescriptionStutas !== 3 && record.cancelPrescription !== 2) {
                        return '等待买家付款';
                    }
                }
            },
            {
                title: '订单状态', dataIndex: '', width: '10%', render(record) {
                    let text;
                    if (record.cancelPrescription === 2) {
                        text = '已取消';
                    } else if (record.prescriptionStutas === 2) {
                        text = '待核单';
                    }
                    return text;
                }
            },
            {
                title: '下单时间', width: '16%', dataIndex: '', render(record) {
                    return moment(Number(record.orderDate)).format('YYYY-MM-DD HH:mm')
                }
            },
            {
                title: '查看详情', width: '10%', dataIndex: '', render(record) {
                    return <Link to={'/prescriptionDetail/' + record.orderId}>订单详情</Link>
                }
            },
        ];

        //表格行选择
        const { rowKeys } = this.state;
        const rowSelection = {
            rowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
                disabled: record.prescriptionStutas !== 2 || record.cancelPrescription === 2,
            }),
        };
        return (
            <div className='contentBox clearfix'>
                <div className='breadcrumb'>
                    <Breadcrumb separator=">">
                        <Breadcrumb.Item>订单管理</Breadcrumb.Item>
                        <Breadcrumb.Item>订单列表</Breadcrumb.Item>
                    </Breadcrumb>
                </div>
                <div className='orderfilter'>
                    <div className='member-content-Search clearfix' style={{ marginBottom: 20 }}>
                        <div className='addetd  addetd-ght addetd-apples'>
                            <InputGroup compact>
                                <span className='chengge-a chengge-a-de chengge-c-ud' style={{ textAlign:'center'}}>开始时间</span>
                                <DatePicker format='YYYY-MM-DD' value={this.state.beginDate} onChange={this.changeFilterTime.bind(this, 0)} allowClear />
                            </InputGroup>
                        </div>
                        <div className='addetd  addetd-ght addetd-apples'>
                            <InputGroup compact>
                                <span className='chengge-a chengge-a-de chengge-c-ud' style={{ textAlign:'center'}}>结束时间</span>
                                <DatePicker format='YYYY-MM-DD' value={this.state.endDate} onChange={this.changeFilterTime.bind(this, 1)} allowClear />
                            </InputGroup>
                        </div>
                        <div className='addetd  addetd-ght addetd-apples boye-tml'>
                            <InputGroup compact>
                                <span className='chengge-a chengge-a-de chengge-c-ud' style={{ textAlign:'center'}}>处方状态</span>
                                <Select placeholder='请选择' style={{ width: 120 }} value={this.state.status} allowClear onChange={this.changeCFstate.bind(this)}>
                                    <Option value='1'>待审核</Option>
                                    <Option value='2'>审核通过</Option>
                                    <Option value='3'>审核不通过</Option>
                                </Select>
                            </InputGroup>
                        </div>
                        <div className='addetd  addetd-ght addetd-apples boye-tml'>
                            <InputGroup compact>
                                <span className='chengge-a chengge-a-de chengge-c-ud' style={{ textAlign:'center'}}>订单状态</span>
                                <Select placeholder='请选择' style={{ width: 120 }} value={this.state.orderStatus} allowClear onChange={this.changeorderStatus.bind(this)}>
                                    <Option value='待核单'>待核单</Option>
                                    <Option value='已取消'>已取消</Option>
                                </Select>
                            </InputGroup>
                        </div>
                        <Button style={{ marginLeft: 20 }} type='primary' className='member-button' icon="search" onClick={this.filterOrders.bind(this, 1)}>查询</Button>
                        <Button style={{ marginLeft: 20 }} type='primary' className='member-button' icon="reload" onClick={this.filterOrders.bind(this, 0)}>重置</Button>
                    </div>
                    <div style={{ textAlign: 'right', padding: '5px 50px 5px 5px', background: '#e4ebf4', width: '100%', float: 'left', height: 40, lineHeight: '30px', marginBottom: 20 }}>
                        所查询订单合计金额：<i style={{ color: '#ff0000', fontStyle: 'normal' }}>{this.state.totalMoney}</i>元
                    </div>
                    <div className='allgoods-table clearfix'>
                        <Table rowSelection={rowSelection} columns={columns} dataSource={this.state.data} pagination={false} bordered />
                    </div>
                    <div className='center' >
                        <Button type='primary' style={{ marginTop: 30 }} onClick={this.penddingManyOrder.bind(this)}>批量审核订单</Button>
                    </div>
                    <div className='goods-label-let clearfix'>
                        <div className="floor-ppagi">
                            {
                                this.state.total == 0 ?
                                    <p className="floor-ppagip">
                                        共{this.state.total}条记录
                                </p> :
                                    <p className="floor-ppagip">
                                        当前显示
                                    {this.state.pageSize * (this.state.page - 1) + 1}—
                                    {this.state.pageSize * this.state.page < this.state.total ? this.state.pageSize * this.state.page : this.state.total}条记录，
                                    共{this.state.total}条记录
                                </p>
                            }
                            <Pagination current={this.state.page} total={this.state.total || 1} defaultPageSize={this.state.pageSize} onChange={this.onChangePage.bind(this)} />
                        </div>
                    </div>
                </div>
            </div >
        )
    }
}

export default Prescription;